// spMain.js

function spAjaxUrl( param )
{
	urlparam = "";
	
	if ( param!=undefined )
		urlparam = "&"+jQuery.param(param);

	return spHome+"/wp-admin/admin-ajax.php?action=sp_ajax_response"+urlparam;
}

function resetFormErrors( form )
{
	form.find(".formError").removeClass( "formError" );
}

function processFormErrors( errors )
{
	for ( i=0; i<errors.length; i++ )
	{
		jQuery( ".form_"+errors[i] ).addClass( "formError" );
	}
}

function spAjaxCallback( param )
{
	more = "";
	
	if ( param.param!=undefined )
		more = "&"+jQuery.param(param.param);

	if ( param.paramstr!=undefined )
		more = "&"+param.paramstr;
		
	showDlg = param.dialog!=undefined ? param.dialog:true;
		
	data = "callback="+param.callback+more;
	
	if ( showDlg )
		spOpenDialog( param.title );
	
	jQuery.ajax({
		url 		: spHome+"/wp-admin/admin-ajax.php?action=sp_ajax_response",
		data 		: data,
		dataType 	: "json",
		type 		: "POST",
		success		: function(data){
			param.success();
			
			// redirect
			if ( data && data.redirect!=undefined )
				window.location = "admin.php?page="+data.redirect;
		},
		error 		: function(XMLHttpRequest, textStatus, errorThrown){
			jQuery( "#spErrorMsg" ).html( "<b>spAjaxCallback Error:</b><br/>" );
			jQuery( "#spErrorMsg" ).append( XMLHttpRequest.responseText );
			jQuery( "#spErrorMsg" ).append( textStatus );
			jQuery( "#spErrorMsg" ).append( errorThrown );
		},
		complete 	: function(){
			spCloseDialog();
		}
	});		
}


function spShowLoading( selector )
{
	jQuery(selector).html(
		"<img src='"+spHome+"/wp-content/plugins/sigmaphp/images/ajax-loader.gif' alt=''/>"
	);
}

function spShowLoadingBar( selector )
{
	jQuery(selector).html(
		"<img src='"+spHome+"/wp-content/plugins/sigmaphp/images/bar-loader.gif' alt=''/>"
	);
}

function spLoadOnly( selector, callback, data )
{
	jQuery( selector ).load( spHome+"/wp-admin/admin-ajax.php?action=sp_ajax_response&formType=loadonly&loadonly="+callback, data );
}

function spOpenDialog( title )
{
	jQuery( "#spDialogModal" ).dialog({
		title			: title,
		resizable		: false,
		closeOnEscape	: false,
		open			: function(event, ui){ 
			jQuery(".ui-dialog-titlebar-close").hide(); 
		}
	});
	jQuery( "#spDialogModal" ).dialog( "open" );
}

function spCloseDialog()
{
	jQuery( "#spDialogModal" ).dialog( "close" );
}

function spInit()
{
	jQuery(".tablesorter").tablesorter();
	
	jQuery( ".spTab" ).tabs();
	
	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// media upload
	//
	////////////////////////////////////////////////////////////////////////////////////////////////
	
	var selFormBuilderImageUrl = "";
	jQuery('.spFormBuilderImageButton').click(function() {
	
		selFormBuilderImageUrl = jQuery(this).parents( "div:first" ).find( ".spFormBuilderImageUrl" );
	
	//	formfield = jQuery('#upload_image').attr('name');
		//tb_show('Tumbling Team Fyn', 'media-upload.php?type=image&amp;TB_iframe=true&post_id=1');
		tb_show('Tumbling Team Fyn', 'media-upload.php?type=image&amp;TB_iframe=true');
		return false;
	});

	window.send_to_editor = function(html) {
		imgurl = jQuery('img',html).attr('src');
		//jQuery('#upload_image').val(imgurl);
		selFormBuilderImageUrl.val(imgurl);
		tb_remove();
	}

	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// jPicker (color picker)
	//
	////////////////////////////////////////////////////////////////////////////////////////////////

	jQuery( ".spColorPicker_org" ).jPicker({
		images :{
			clientPath : spHome+"/wp-content/plugins/sigmaphp/ext/jpicker-1.1.6/images/"
		},
		window: {
			expandable : true,
			position : {
				x : "screenCenter",
				y : "center"							
			},
			effects : {
				type : "show",
				speed : {
					show : "fast",
					hide : "fast"
				}
			}
		}
	});

	jQuery( ".spColorPicker_test" ).on( "click", function(){
		alert(1);
	});
	
	
	jQuery( ".spColorPicker" ).jPicker({
		images :{
			clientPath : spHome+"/wp-content/plugins/sigmaphp/ext/jpicker-1.1.6/images/"
		},
		window: {
			expandable : true,
			position : {
				x : "screenCenter",
				y : "center"							
			},
			effects : {
				type : "show",
				speed : {
					show : "fast",
					hide : "fast"
				}
			}
		}}
	);
	
	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// hide the modal dialog
	//
	////////////////////////////////////////////////////////////////////////////////////////////////

	jQuery( "#spDialogModal" ).dialog({
            height		: 100,
            modal		: true,
			autoOpen 	: false
	});
	
	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// datepicker
	//
	////////////////////////////////////////////////////////////////////////////////////////////////

	jQuery( ".spDate" ).datepicker({
		dateFormat		: "dd-mm-yy",
		defaultDate		: jQuery(".spDate").val(),
		showOn			: "button",
		buttonImage		: spHome+"/wp-content/plugins/sigmaphp/images/calendar.png",
		buttonImageOnly	: true,
		changeMonth		: true,
		changeYear		: true,
		yearRange		: "1940:2030"
	});	
}

jQuery(document).ready(function(){

	spInit();
	
	jQuery( document ).on( "click", ".checkboxselectall-parent-parent", function(event){
		jQuery(this).parent().parent().find(':checkbox').prop('checked', this.checked);
	});
	
	jQuery( document ).on( "click", ".quick-checkboxselectall-parent-parent", function(event){
		var id = jQuery(this).attr( "data-group" );
		jQuery("#"+id).parent().parent().find(':checkbox').prop('checked', this.checked);
	});	
	
	jQuery( ".spResetDatabase" ).on( "click", function(e){
	
		name 		= jQuery(this).attr( "data-name" );
		database	= jQuery(this).attr( "data-database" );
		callback	= jQuery(this).attr( "name" );
		
		if ( confirm( 'Are you sure you want to reset the database: '+name ) )
		{
			spAjaxCallback({ 
				callback 	: callback, 
				param		: [
						{ name:'database', 	value:database }
					],
				title		: 'Reseting...',
				success		: function(){
					alert( "Database: "+database+" has been reset" );
				}
			});
		}
		
		return false;
	});
	
	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// handle ajax loading
	//
	// i.e. <div class="ajax-loadme"></div> will call function loadme and insert result into div
	//
	// DEPRECATED: still used in ksprojectsoverview.php, need to remove this at some point
	// 
	////////////////////////////////////////////////////////////////////////////////////////////////
	
	jQuery('*[class^="ajax-"]').each(function(){

		jQuery(this).append( "<img src='"+spHome+"/wp-content/plugins/sigmaphp/images/ajax-loader.gif' alt=''/>" );
	
		loadonly = jQuery(this).attr("class").substring(5);
		
		jQuery( this ).load( spHome+"/wp-admin/admin-ajax.php?action=sp_ajax_response&formType=loadonly&loadonly="+loadonly, function(response, status, xhr){
	
			spInit();
	
			if ( status=="error" ){
				// alert( "error" );
			}
			else {
				// window.location = "admin.php?page=ksprojects";
				// alert( "success" );
			}
		});
	});	

	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// handle ajax click (spAjaxClick)
	//
	//	ex. class="spAjaxClick-myFunction-#myid"
	//
	// DEPRECATED: removing it.. doesn't seem to be used anywhere
	//
	////////////////////////////////////////////////////////////////////////////////////////////////
	/*
	jQuery( '*[class^="spAjaxClick-"]' ).on( "click", function(e) {
	
		arr = jQuery(this).attr("class").split("-");
		callback = arr[1];
		div_id = arr[2];
		
		jQuery( div_id ).load( spHome+"/wp-admin/admin-ajax.php?action=sp_ajax_response&formType=loadonly&loadonly="+callback, function(response, status, xhr){
	
			if ( status=="error" ){
				 //alert( "error" );
			}
			else {
				// window.location = "admin.php?page=ksprojects";
				 //alert( "success" );
			}
		});
	});
	*/
	
	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// handle redirect
	//
	////////////////////////////////////////////////////////////////////////////////////////////////

	jQuery( ".spRedirectAdmin" ).on( "click", function(e) {
		window.location = "admin.php?page="+jQuery(this).attr( "name" );
	});

	jQuery( ".spRedirectUrl" ).on( "click", function(e) {
		window.location = jQuery(this).attr( "name" );
	});

	/*
	
	DEPRECATED: doesn't seem to be used anymore
	
	// FIXME: it needs a title and delete confirmation,,,perhaps i should move this to the spgui javascript
	jQuery( ".spCallback" ).on( "click", function(e) {
	
		param = "";
	
		dg = jQuery(this).attr( "data-groupname" );
		
		jQuery(document).find( "[data-group="+dg+"]" ).each(function(){

			if ( jQuery(this).hasClass("spGuiListBox") )
			{
				name = jQuery(this).attr("data-guilistbox-name");
				jQuery(this).find( "[data-selected=true]" ).each(function(){
					param += name+"="+jQuery(this).attr("data-id");
				});
			}
		});
		
			
	});
	*/
	
	
	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// handle ajax form
	//
	//	DEPRECATED: doesn't seem to be used anymore (used in kosangas)
	//
	////////////////////////////////////////////////////////////////////////////////////////////////
	
	jQuery( ".spAjaxForm" ).on( "click", function(e) {

		// prevents the page from reloading
		e.preventDefault();			

		buttonPressedName = jQuery(this).attr("name");

		spOpenDialog( "Saving..." );

		form = jQuery( this ).parents("form:first");
		var ser = jQuery( this ).parents("form:first").serialize();

		resetFormErrors( form );
		
		jQuery.ajax({
			url 		: spHome+"/wp-admin/admin-ajax.php?action=sp_ajax_response",
			data 		: ser+"&formType="+jQuery( this ).parents("form:first").attr("name")+"&button="+buttonPressedName,
			dataType 	: "json",
			type 		: "POST",
			success		: function(data){
				
				if ( data.formerrors!=undefined )
				{
					processFormErrors( data.formerrors );
				}
			
				//jQuery( "#spErrorMsg" ).html( "<pre>"+JSON.stringify( data, null, 2 )+"</pre>" );
				
				if ( data.loadonly!=undefined )
				{
					spLoadOnly( data.loadonly.sel, data.loadonly.callback, data.loadonly.data );
				}
				
				if ( data.redirect!=undefined )
				{
					//alert(data.redirect);
					//jQuery( ".spPage" ).html("<img src='"+spHome+"/wp-content/plugins/sigmaphp/images/bar-loader.gif'/>");
					jQuery( ".spPage" ).html("<img src='"+spHome+"/wp-content/plugins/sigmaphp/images/bar-loader.gif'/>");
					
					setTimeout(function() {
						// Insert code to be executed AFTER
						// the page renders the markup
						// added using html(...) here
						window.location = "admin.php?page="+data.redirect;
						return false;
					}, 1);
				}

				if ( data.redirect_url!=undefined )
				{
					jQuery( ".spPage" ).html("<img src='"+spHome+"/wp-content/plugins/sigmaphp/images/bar-loader.gif'/>");
					window.location = data.redirect_url;
				}

				if ( data.message!=undefined )
				{
					jQuery( data.message.sel ).html( "<p>"+data.message.text+"</p>" );
				}
				
				if ( data.javascript_call!=undefined )
				{
					window[data.javascript_call]();
				}
			},
			error 		: function(XMLHttpRequest, textStatus, errorThrown){
				jQuery( "#spErrorMsg" ).html( 
					"AJAX ERROR:<br/><textarea>"+XMLHttpRequest.status+"</textarea>" +
					"<textarea>"+textStatus+"</textarea>" +
					"<textarea>"+XMLHttpRequest.responseText+"</textarea>"+
					"<textarea>"+errorThrown+"</textarea>"
				);
				
				jQuery( "#spErrorMsg" ).html( XMLHttpRequest.responseText );
			},
			complete 	: function()
			{
				spCloseDialog();
			}
		});		
				
		return false;
	});		
	
});